package com.hui.service.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.reflect.TypeToken;
import com.hui.dao.MusicWebMapper;
import com.hui.domain.Mid;
import com.hui.domain.Song;
import com.hui.domain.Upload;
import com.hui.domain.User;
import com.hui.service.MusicWebService;
import com.hui.utils.JSONUtils;
import com.hui.utils.UUIDUtils;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author Ayingzz
 * @create 2021/12/25 16:50
 */
@Service
public class MusicWebServiceImpl implements MusicWebService {

    @Autowired
    private MusicWebMapper musicWebMapper;

    /**
     * 查询所有歌曲
     * @return
     */
    public List<Song> queryAllSongs() {
        return musicWebMapper.queryAllSongs();
    }

    /**
     * 查询所有歌曲类型
     * @return
     */
    public Set<String> queryAllTypes() {
        return musicWebMapper.queryAllTypes();
    }

    /**
     * 根据关键字查询歌曲
     * @param keyword
     * @return
     */
    public List<Song> querySongByKeyword(String keyword) {
        return musicWebMapper.querySongByKeyword(keyword);
    }

    /**
     * 根据类型查询歌曲
     * @return
     */
    public List<Song> querySongByType(String type) {
        return musicWebMapper.querySongByType(type);
    }

    /**
     * 根据用户名查询歌曲（我的喜欢）
     * @param uname
     * @return
     */
    public List<Song> querySongByUname(String uname) {
        String favourite = musicWebMapper.querySongByUname(uname);
        // 将查到的Json字符串转换成List
        List<?> midList = new JSONUtils().toJSONListByGson(favourite, new TypeToken<List<Mid>>(){}.getType());
        // 返回用id组查询得到的歌曲列表
        return querySongByMidGroup((List<Mid>) midList);
    }

    /**
     * 根据歌曲id查询歌曲
     * @param mid
     * @return
     */
    public Song querySongByMid(String mid) {
        return musicWebMapper.querySongByMid(mid);
    }

    /**
     * 根据歌曲id组查询歌曲
     * @param midList
     * @return
     */
    public List<Song> querySongByMidGroup(List<Mid> midList) {
        return musicWebMapper.querySongByMidGroup(midList);
    }

    /**
     * 收藏歌曲或取消收藏（我的喜欢）
     * @param uname
     * @return
     */
    public int addOrDeleteSongFromFavouriteListByUname(String uname, String mid) {
        String favourite = musicWebMapper.querySongByUname(uname);
        // 将查到的Json字符串转换成List
        int flag = 0;
        List<Mid> midList = null;
        // 歌曲在 我的喜欢 里
        if (favourite.contains(mid)) {
            midList = (List<Mid>) new JSONUtils().toJSONListByGson(favourite, new TypeToken<List<Mid>>(){}.getType());
            int removeIndex = 0;
            for (Mid m : midList) {
                if (mid.equals(m.mid)) {
                    removeIndex = midList.indexOf(m);
                    break;
                }
            }
            midList.remove(removeIndex);
        } else { // 歌曲不在 我的喜欢 里
            if ("".equals(favourite)) {
                midList = new ArrayList<>();
                midList.add(new Mid(mid));
            } else {
                midList = (List<Mid>) new JSONUtils().toJSONListByGson(favourite, new TypeToken<List<Mid>>(){}.getType());
                midList.add(new Mid(mid));
            }
            flag = 1;
        }
        // 将List转换为Json字符串
        String favouriteStr = new JSONUtils().toJSONStrByGson(midList, new TypeToken<List<Mid>>(){}.getType());
        // 更新我的喜欢
        musicWebMapper.updateFavouriteByUname(uname, favouriteStr);
        return flag;
    }

    /**
     * 根据歌曲id增加播放次数
     * @param mid
     * @return
     */
    public List<Song> addPlayTimesByMid(String mid) {
        // 增加次数
        musicWebMapper.addPlayTimesByMid(mid);
        // 返回列表
        return musicWebMapper.queryAllSongs();
    }

    /**
     * 添加歌曲
     * @param songStr
     * @return
     */
    public int insertSong(String songStr, Upload upload) throws IOException {
        // 基本信息包装
        songStr = songStr.substring(1, songStr.length() - 1);
        ObjectMapper mapper = new ObjectMapper();
        Song song = mapper.readValue(songStr, Song.class);
        // 上传图片
        MultipartFile imgFile = upload.getImgFile();
        if (imgFile != null) {
            // 存储路径
            String filepath="D:/ideaProject/MusicWebSpringboot/image/";
            File imageFolder = new File(filepath + song.getMusicName() + ".png");
            if (!imageFolder.getParentFile().exists()) {
                imageFolder.getParentFile().mkdirs();
            }
            imgFile.transferTo(imageFolder); // 方法一
            /**
             * 方法二
             * FileUtils.copyInputStreamToFile(imgFile.getInputStream(), imageFolder)
             */
            song.setMusicImg(song.getMusicName() + ".png");
        } else {
            System.out.println("图片文件为空");
            return 0;
        }
        // 设置歌词
        MultipartFile lyricFile = upload.getLyricFile();
        if (lyricFile != null) {
            InputStream inputStream = lyricFile.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            String lineTxt;
            StringBuilder stringBuilder = new StringBuilder();
            while ((lineTxt = bufferedReader.readLine()) != null) {
                stringBuilder.append(lineTxt.replace(" ", "1"));
                stringBuilder.append(" ");
            }
            song.setMusicLyric(stringBuilder.toString());
        } else {
            System.out.println("歌词文件为空");
        }
        // 设置UUID
        song.setMid(UUIDUtils.getUUID());
        // 添加歌曲
        return musicWebMapper.insertSong(song);
    }

    /**
     * 根据歌曲id编辑歌曲
     * @param songStr
     * @return
     */
    public int updateSongByMid(String songStr) throws JsonProcessingException {
        // 基本信息包装
        songStr = songStr.substring(1, songStr.length() - 1);
        ObjectMapper mapper = new ObjectMapper();
        Song song = mapper.readValue(songStr, Song.class);
        // 编辑歌曲
        return musicWebMapper.updateSongByMid(song);
    }

    /**
     * 根据id删除歌曲
     * @param mid
     * @return
     */
    public int deleteSongByMid(String mid) {
        mid = mid.replace("{", "").replace("mid", "")
                .replace("mid", "").replace(":", "")
                .replace("\"", "").replace("}", "");
        System.out.println(mid);
        return musicWebMapper.deleteSongByMid(mid);
    }

    /**
     * 增加一个用户
     * @param userStr
     * @return
     */
    public User insertUser(String userStr) throws JsonProcessingException {
        System.out.println("userStr:" + userStr);
        // 基本信息包装
        userStr = userStr.substring(1, userStr.length() - 1);
        ObjectMapper mapper = new ObjectMapper();
        User user = mapper.readValue(userStr, User.class);
        System.out.println(user.toString());
        // 设置UUID
        user.setUid(UUIDUtils.getUUID());
        // 添加用户
        int count = musicWebMapper.insertUser(user);
        return count != 0 ? user : null;
    }

    /**
     * 匹配用户（登录）
     * @param uname
     * @param upass
     * @return
     */
    public String checkUserByUname(String uname, String upass) {
        return musicWebMapper.checkUserByUname(uname, upass);
    }
}
